package com.sch.www.common.util.io;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;


/**
 * Created by Administrator on 2017-05-13.
 */
public class ResourceUtil {

    private static final Logger log = LoggerFactory.getLogger(ResourceUtil.class);
    public static final String CLASSPATH_PREFIX = "classpath:";
    public static final String URL_PREFIX = "url:";
    public static final String FILE_PREFIX = "file:";

    private ResourceUtil() {
    }

    public static boolean hasResourcePrefix(String resourcePath) {
        return resourcePath != null && (resourcePath.startsWith("classpath:") || resourcePath.startsWith("url:") || resourcePath.startsWith("file:"));
    }

    /**
     * 判断文件是否存在
     * @param resourcePath
     * @return
     */
    public static boolean resourceExists(String resourcePath) {
        InputStream stream = null;
        boolean exists = false;

        try {
            stream = getInputStreamForPath(resourcePath);
            exists = true;
        } catch (IOException var12) {
            stream = null;
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException var11) {
                    ;
                }
            }

        }

        return exists;
    }

    /**
     *获取文件输入流
     * @param resourcePath
     * @return
     * @throws IOException
     */
    public static InputStream getInputStreamForPath(String resourcePath) throws IOException {
        InputStream is;
        if (resourcePath.startsWith("classpath:")) {
            is = loadFromClassPath(stripPrefix(resourcePath));
        } else if (resourcePath.startsWith("url:")) {
            is = loadFromUrl(stripPrefix(resourcePath));
        } else if (resourcePath.startsWith("file:")) {
            is = loadFromFile(stripPrefix(resourcePath));
        } else {
            is = loadFromFile(resourcePath);
        }

        if (is == null) {
            throw new IOException("Resource [" + resourcePath + "] could not be found.");
        } else {
            return is;
        }
    }

    /**
     * 读取文件系统文件
     * @param path
     * @return
     * @throws IOException
     */
    private static InputStream loadFromFile(String path) throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("Opening file [" + path + "]...");
        }
        return new FileInputStream(path);
    }

    /**
     * 读取网络文件
     * @param urlPath
     * @return
     * @throws   IOException
     */
    private static InputStream loadFromUrl(String urlPath) throws IOException {
        log.debug("Opening url {}", urlPath);
        URL url = new URL(urlPath);
        return url.openStream();
    }

    /**
     * 读取类加载器下的文件
     * @param path
     * @return
     */
    private static InputStream loadFromClassPath(String path) {
        log.debug("Opening resource from class path [{}]", path);
        return ResourcesUtilBase.getResourceAsStream(path);
    }


    private static String stripPrefix(String resourcePath) {
        return resourcePath.substring(resourcePath.indexOf(":") + 1);
    }


    /**
     * 关闭输入流的工具方法
     * @param is
     */
    public static void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException var2) {
                log.warn("Error closing input stream.", var2);
            }
        }
    }


    /**
     * 关闭输出流的工具方法
     * @param os
     */
    public static void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException var2) {
                log.warn("Error closing Output stream.", var2);
            }
        }

    }

    //=================================================================

    /**
     * 保存到指定文件
     * @param is  文件的输入流
     * @param targetFullPath  文件保存全路径(路径+文件名)
     * @return
     */
    public static boolean saveFile(InputStream is, String targetFullPath) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(targetFullPath);
            byte[] tempbytes = new byte[1024];
            int byteread = 0;
            while ((byteread = is.read(tempbytes)) != -1) {
                out.write(tempbytes);
            }
        } catch (Exception e) {
            log.warn("【Manual】=>附件读取失败{}", e.getMessage());
            return false;
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                log.warn("【Manual】=>{}", e.getMessage());
            }
            try {
                is.close();
            } catch (Exception e) {
                log.warn("【Manual】=>{}", e.getMessage());
            }
        }
        return true;
    }



    //=================================================================

//
//    /**
//     * 创建目录
//     *
//     * @param dirFile
//     * @return
//     * @throws RuntimeException
//     */
//    public static boolean createDir(File dirFile) throws RuntimeException {
//        boolean flag = false;
//        if (dirFile.exists()) {
//            flag = true;
//        } else {
//            flag = dirFile.mkdirs();
//        }
//        return flag;
//    }
//
//    /**
//     * 删除目录
//     *
//     * @param dirFile
//     * @return
//     * @throws RuntimeException
//     */
//    public static boolean deleteDir(File dirFile) throws RuntimeException {
//        boolean flag = false;
//        if (!dirFile.exists()) {
//            flag = true;
//        } else {
//            if (deleteSubFiles(dirFile)) {
//                flag = dirFile.delete();
//            }
//        }
//        return flag;
//    }
//
//    /**
//     * 清空指定目录下的所有文件
//     *
//     * @param dir
//     */
//    public static boolean deleteSubFiles(File dir) {
//        log.debug("开始清除{}下的所有文件", dir.getAbsolutePath());
//        boolean flag = false;
//        if (dir.exists() && dir.isDirectory()) {
//            File[] subs = dir.listFiles();
//            int succ = 0;
//            int fail = 0;
//            int length = subs == null ? 0 : subs.length;
//            File sub = null;
//            try {
//                for (int i = 0; i < length; i++) {
//                    sub = subs[i];
//                    if (sub.delete()) {
//                        succ++;
//                    } else {
//                        fail++;
//                    }
//                }
//                flag = true;
//            } catch (Exception e) {
//                log.error("清除{}下的" + sub.getAbsolutePath() + "文件失败，原因是：{}",
//                        dir.getAbsolutePath(), e);
//            }
//            log.debug("清除{}下的所有文件, 成功{}个", dir.getAbsolutePath(), succ);
//            log.debug("清除{}下的所有文件, 失败{}个", dir.getAbsolutePath(), fail);
//        }
//        return flag;
//    }
//
//    /**
//     * 获取指定文件的扩展名
//     *
//     * @param fileName
//     * @return
//     */
//    public static String getExtend(String fileName) {
//        return fileName.substring(fileName.lastIndexOf('.'));
//    }
//
//    /**
//     * 使用当前日期时间来产生"yyyyMMddHHmmssSSS"的字符串，主要用来做文件名
//     *
//     * @return
//     */
//    public static String generateFileNameByDateTime() {
//        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//    }
//
//    /**
//     * 把源文件的内容复制到目标文件
//     *
//     * @param src
//     *            源文件
//     * @param dest
//     *            目标文件
//     */
//    public static void copy(File src, File dest) throws IOException {
//        BufferedInputStream bis = null;
//        BufferedOutputStream bos = null;
//        byte[] b = new byte[8192];
//        try {
//            bis = new BufferedInputStream(new FileInputStream(src));
//            bos = new BufferedOutputStream(new FileOutputStream(dest));
//
//            for (int count = -1; (count = bis.read(b)) != -1;) {
//                bos.write(b, 0, count);
//            }
//            bos.flush();
//        } catch (IOException e) {
//            throw e;
//        } finally {
//            close(bis);
//            close(bos);
//        }
//    }







}